package com.hyts.dess.websocket.interceptor;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import javax.servlet.http.HttpSession;

import com.hyts.dess.websocket.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Slf4j
public class DessHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    /**
     * 前置握手的操作处理服务切入点
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes)
            throws Exception {
        log.info("前置操作处理服务切入点");
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            if (Objects.nonNull(session)) {
                String username = Optional.ofNullable((String) session.getAttribute(Constants.DEFAULT_SESSION_USERNAME)).orElse(Constants.DEFAULT_EMPTY_USER_NAME_VALUE);
                attributes.put(Constants.DEFAULT_WEBSOCKET_USERNAME, username);
            }
        }
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    /**
     * 后置握手的操作处理服务切入点
     * @param request
     * @param response
     * @param wsHandler
     * @param ex
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        log.info("后置操作处理服务切入点");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
